Passed
Push — main ( eb8b76...ea2980 )
by Andrii
02:38
created

map.ts ➔ mapping   A

Complexity

Conditions 4

Size

Total Lines 31
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 31
c 0
b 0
f 0
rs 9.256
cc 4
1
import {
2
  CssModule,
3
} from "./definitions.types";
4
import type {
5
  ClassNamesMapping, ClassNamesMap,
6
} from "./naming.types";
7
import {resolver} from "./core"
8
import { AnyObject, OmitIndexed } from "./ts-swiss.types";
9
import { GetProps } from "./react-swiss.types";
10
11
const {keys: $keys} = Object
12
13
export {
14
  classNamesMap
15
}
16
17
/**
18
 * Set up mapping classnames function
19
 * @example
20
 * ```typescript
21
 * const mapping = classNamesMap(classnames)
22
 * ```
23
 */
24
function classNamesMap<
25
  Source extends CssModule,
26
>(classnames: Source){
27
  const mapper: ClassNamesMapping<Source> = (target, map) => mapping(classnames, target, map)
28
  return mapper
29
}
30
31
function mapping<
32
  Source extends CssModule,
33
  Target extends AnyObject,
34
  Mapping extends ClassNamesMap<OmitIndexed<GetProps<Target>>, Source>
35
>(
36
  source: Source,
37
  _: Target,
38
  map: Mapping
39
): {[M in keyof Mapping]: string} {
40
  // TODO change to for-in https://jsbench.me/prkm3gn4ji
41
  const keys = $keys(map) as (keyof Mapping)[]
42
  // TODO  = {...keys} + reassign or delete?
43
  , classnames = {} as {[M in keyof Mapping]: string}
44
45
  for (let i = keys.length; i--;) {
46
    const key = keys[i]
47
    , val = map[key]
48
    
49
    if (val === undefined)
50
      continue
51
      
52
    classnames[key] = typeof val === "function"
53
    ? `${val}`
54
    : resolver(source,
55
      //@ts-expect-error #27 TS doesn't understand that ClassNaming is first of all function
56
      val
57
    ).join(" ") 
58
  }
59
60
  return classnames
61
}
62